<?php
/*
 * @Author: CHINAKAIYUAN<sunkaiyuan@namenode.cn>
 * @Date: 2022-02-04 16:53:56
 * @LastEditTime: 2023-11-09 15:45:37
 * @LastEditors: 孙开源 && sunkaiyuan@namenode.cn
 * @Description: 
 */

namespace App\Http\Services\Pro;


use App\Http\Services\Service;
use App\Repositories\ProProcessesPassRepository;
use App\Repositories\ProProcessesStorageRepository;

use Illuminate\Support\Facades\DB;

/**
 * @property ProProcessesStorageRepository $repository
 * @property ProProcessesPassRepository $pass
 * @author sunkaiyuan
 */
class ProcessesStorageService extends Service
    {
    public function __construct(ProProcessesStorageRepository $repository, ProProcessesPassRepository $pass)
        {
        $this->repository = $repository;
        $this->pass       = $pass;

        }
    protected function save()
        {
        $data   = request()->toArray();
        $wip_id = $data["wip_id"][0];

        // $data['car_id']   = ($data['car_id'] ?? "") == "" ? 0 : $data['car_id'];
        // $data['carry_id'] = ($data['carry_id'] ?? "") == "" ? 0 : $data['carry_id'];

        $pass                 = $this->pass->swipe($wip_id, $data['quantity'], 0, $data['direction_id'], $data['pro_dept_id'], null, null, null, $data['material_quantity'], $data['location_id']);
        $gdata                = $pass->target;
        $gdata['attachments'] = $data['attachments'];
        // $gdata = $this->repository->autosave($data);

        $gdata = $gdata->toArray();
        //搬运
        $gdata['car']   = $data['car'];
        $gdata['carry'] = $data['carry'];

        $gdata = $this->repository->autosave($gdata);

        $gdata->carry_id > 0 && $gdata->addCarryItem();
        //运输
        $gdata->car_id > 0 && $gdata->addCarItem($gdata->outfactory->name, $gdata->location->name);

        return $gdata;
        }

    public function list()
        {
        $data = $this->repository->condition(request())->getGrid();
        return $data;
        }
    protected function faudit()
        {
        $financeremark = request('financeremark');
        return $this->repository->whereIn("id", $this->getRequestIds())->get()->map(function ($item) use ($financeremark)
            {
            if ($item->status_id != 0) {
                fail("单据{$item->status->name},审核失败！");
                }
            auditSave($item);
            $item->financeremark = $financeremark;
            $item->finance();
            });
        }

    protected function delete()
        {
        return $this->repository->whereIn("id", $this->getRequestIds())->get()->map(function ($item)
            {
            if ($item->status_id != 0 && $item->direction_id == 1) {
                fail("工序外发收货已[{$item->status->name}],禁止删除！");
                }
            $this->pass->deletePass($item->pass_id);
            });
        }
    }